<?php
declare (strict_types = 1);
namespace app\api\logic;
use app\admin\model\Goods;
use app\admin\model\GoodsCat;
use app\admin\model\GoodsSpecs;
use app\common\model\GoodsCollect;
class GoodsLogic
{	

	 function lists($args = []){
    	 $order = "is_top desc,id desc";
    	 $w['status'] = 1;
    	 if(isset($args['cid']) && $args['cid']>0){
    	 	 $w['cat_id'] = intval($args['cid']);
    	 }
    	 $w['shop_id'] = $args['shop_id'];
    	 $res = Goods::where($w)->order($order)->select();
    	 return $res;
	 }
	 //详细
	 function details($args = []){
	 	 if(isset($args['pid'])){
    	 	 $w['id'] = intval($args['pid']);
    	 	 $w['shop_id'] = $args['shop_id'];
    	 	 $w['status'] = 1;
    	 }else{
    	 	 return ['code'=>100,'back_type'=>1,'msg'=>'记录不存在或已下架'];
    	 }
    	 $res = Goods::where($w)->find()->toArray();
    	 if($res){
    	 	 if($res['specs'] == 1){
    	 	 	  $res['specs_details'] = GoodsSpecs::where("goods_id",$res['id'])->order("sort desc")->select();
    	 	 }
    	 	 if($res['imgs']){
    	 	 	 $res['imgs'] = explode("#",$res['imgs']);
    	 	 	 $imgs = $res['imgs'];
    	 	 	 foreach($imgs as &$v){
    	 	 	 	   $lists[] = 'http://yunlai_shop.com'.$v;
    	 	 	 }
    	 	 	 $res['imgs_list'] = $lists ?? [];
    	 	 }
    	 	 Goods::where($w)->setInc("hits");
    	 }
    	 return $res;
    	 
	 }
	 //分类
	 function cat($args = []){
    	 $order = "sort desc";
    	 $w['status'] = 1;
    	 $w['shop_id'] = $args['shop_id'];
    	 if(isset($args['cid']) && $args['cid']!=0){
    	 	 $w['id'] = intval($args['cid']);
    	 }
    	 $res = GoodsCat::where($w)->order($order)->select();
    	 $childs = [];
    	 foreach($res as &$v){
    	 	  if($v['pid'] > 0){
    	 	  	 $childs[$v['pid']][] = $v;
    	 	  }
    	 }
    	 foreach($res as &$v){
    	 	  if(isset($childs[$v['id']])){
    	 	  	   $v['child'] = $childs[$v['id']];
    	 	  }
    	 }
    	 return $res;
	 }
	 //商品收藏
	 function collect($args = []){
	 		$pid = $args['pid'] ?? 0;
	 		if($pid){
	 			 $pro = Goods::where("id",$pid)->where("shop_id",$args['shop_id'])->find();
 			 	 if(!$pro){
 			 		 return ['code'=>100,'back_type'=>1,'msg'=>'商品不存在或已下架'];
 			 	 }
	 			 $find = GoodsCollect::where(['user_id'=>$args['uid'],'pid'=>$pid])->find();
	 			 if($find){
	 			 	$res = GoodsCollect::where(['user_id'=>$args['uid'],'pid'=>$pid])->delete();
	 			 }else{
	 			 	$res = GoodsCollect::insert([
	 			 		'pid'=>$pid,
	 			 		'user_id'=>$args['uid'],
	 			 		'pro_title'=>$pro['title'],
	 			 		'pro_pic'=>$pro['feng'],
	 			 		'pro_price'=>$pro['price'],
	 			 		'time'=>time()
	 			 	]);
	 			 }

	 			 if($res){
	 			 	 return ['code'=>200,'back_type'=>1,'msg'=>'ok'];
	 			 }else{
	 			 	 return ['code'=>100,'back_type'=>1,'msg'=>'操作失败，请重试'];
	 			 }
	 		}else{
	 			 return ['code'=>100,'back_type'=>1,'msg'=>'操作异常'];
	 		}
	 }
}